<?php
/**
 * vim: et ts=4 sts=4 sw=4 fdm=marker
 *
 * 测试controller 
 *
 * @author	wang Penghai <china_php@hotmail.com>
 * @copyright 2008 5e6d Corporation.
 * @version   $Id: config.php 29 2009-03-10 14:30:18Z wph $
 */
pf_load::init('admin_class_admin');
class class_action extends pf_controller{
	protected $category_obj = null;

	public function __construct()
	{
		parent::__construct();
		$this->category_obj = pf_load::init('content_model_category');
	}

	public function index()
	{
		$category_list = $this->get_category_list();
		$this->assign('category_list', $category_list);
		$this->view('content_admin_view_category.list');
	}


	public function add()
	{
		$opt = pf_request::get('opt', 'list');
		switch ($opt)
		{
			case 'insert':
				$this->insert();
				break;
			case 'update':
				$this->update();
				break;
			default:
				$this->show_add();
				break;
		}
		
	}

	public function show_add()
	{
		$id = (int)pf_request::get('id', 0);
		$opt = "insert";
		$category = array();
		if ($id !== 0)
		{
			$category = $this->category_obj->get_category_by_id($id);
			if (false === $category)
			{
				$category = array();
			}
			$opt = 'update';
		}
		$category_list = $this->get_category_list();
		$this->assign('category_list', $category_list);
		$this->assign('opt', $opt);
		$this->assign('category', $category);
		$this->view('content_admin_view_category.add');
	}

	private function get_category_list()
	{
		$category_list = $this->category_obj->get_category_list();
		foreach ($category_list as $key=>$val)
		{
			$level = $val['level'];
			$str = '';
			if ($level > 1)
			{
				$str = "└";
				for($i=0; $i < $level; $i++)
				{
					$str .= '--';
				}
			}
			$category_list[$key]['name'] = $str . $category_list[$key]['name'];
		}
		return $category_list;
	}
	
	public function update()
	{
		$data['parentid'] = (int)pf_request::post('parentid', 0);
		$data['name'] = pf_request::post('cname', '');

		//$time = time();
		//$data['updatetime'] = $time;
		$id = pf_request::post('id', 0);
		$argv = array(
			'data'=> $data,
			'where' => 'id=' . (int)$id,
		);

		$res = $this->category_obj->update($argv);
		if (false === $res)
		{
			echo "fail";
		} else {
			echo "success";
		}
	}

	public function insert()
	{
		$data['parentid'] = (int)pf_request::post('parentid', 0);
		$data['name'] = pf_request::post('cname', '');

		//$time = time();
		//$data['updatetime'] = $data['createtime'] = $time;
		$res = $this->category_obj->insert($data);
		if (false === $res)
		{
			echo "fail";
		} else {
			echo "success";
		}
	}
}
